package com.epam.qanda.web.servlet.logged;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.qanda.db.model.Category;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.model.UserCategory;
import com.epam.qanda.db.service.UserCategoryService;

public class SubscribeCategoryPageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		User user = (User) request.getSession().getAttribute("user");
		List<Category> all = (List<Category>) request.getSession().getAttribute("categories");
		// ---------- create list of users categories
		List<UserCategory> userCategories = new UserCategoryService().getUserCategories(user
				.getId());
		List<Integer> userCategoriesIds = new ArrayList<>();
		for (UserCategory item : userCategories) {
			userCategoriesIds.add(item.getCategoryId());
		}
		List<Category> categories = new ArrayList<>();
		for (Category item : all) {
			if (userCategoriesIds.contains(item.getId())) {
				categories.add(item);
			}
		}
		request.setAttribute("usersCategories", categories);
		// ---------- create list of categories users not have
		List<Category> nonSelectCategories = new ArrayList<>();
		for (Category item : all) {
			nonSelectCategories.add(item);
		}
		for (Category category : categories) {
			if (nonSelectCategories.contains(category)) {
				nonSelectCategories.remove(category);
			}
		}
		request.setAttribute("nonSelectCategories", nonSelectCategories);
		// ----------
		request.getRequestDispatcher("WEB-INF/pages/manageCategory.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
